%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Module summary
%%
%% Main authors: Peter
%% Progress to usefulness: 
%%
%% Store worker processes is dynamically added when a new
%% socket connection arrives. Calls from socket should go
%% through a store worker.
%%
%%
%% External function calls:
%% 
%% {put, Key, Value} -- Store 'Key' and 'Value' at correct node
%% {get, Key}        -- Get value from node holding 'Key'
%%
%%%%%%%%%%%%%%%%%%%%%%%

-module(store_worker).
-behaviour(gen_server).
-include("db.hrl").

% gen_server API
-export([start_link/0]).

% gen_server API
-export([init/1, handle_call/3,handle_cast/2,handle_info/2
        ,terminate/2, code_change/3]).


start_link() ->
    %io:format("Starting Store Worker\n"),
    gen_server:start_link(?MODULE,[],[]).

% Initial dictionary
% should return {ok, State}
init(State) ->
    {ok, State}.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%   Internal "function calls"
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%
% Handle put
%
%
handle_call({put, Key, Value}, _From, State) ->
    Dest  = gen_server:call(?NETWORK,{lookup, Key}),
    Reply = gen_server:call({?BACKEND,Dest}, {put, Key, Value}),
    visual:visual_element(Key,Value,Dest,[]),
    {reply,Reply, State};
%
% Handle get
%
handle_call({get, Key}, _From, State) ->
    Dest  = gen_server:call(?NETWORK,{lookup, Key}),
    Reply = gen_server:call({?BACKEND,Dest}, {get, Key}),
    {reply, Reply, State}.



%% OTP callback function
handle_cast({stop}, State) ->
    {stop,normal,State};
handle_cast(_Msg, State) ->
    {noreply, State}.

terminate(normal,_State) ->
    ok;
terminate(_Reason,_State) ->
    io:format("Terminating Block Store~n").

handle_info(Info, _State) ->
    io:format("Info message received: ~w~n",[Info]).

code_change(_OldVsn, _State, _Extra) ->
    undefined.
